package jhourglass;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Timer;

import javax.swing.JOptionPane;

import jhourglass.utils.ResourceUtils;

public class JHourGlass {

	int timeInMinute;
	SystemTray tray;
	PopupMenu popup;
	MenuItem startMenuItem;
	MenuItem quitMenuItem;
	Timer timer = new Timer(true);

	TrayIcon trayIcon = null;
	
	Image basicImage = Toolkit.getDefaultToolkit().getImage(
			ResourceUtils.getUrl("resources/hourglass.jpg"));
	
	Image workingImage = Toolkit.getDefaultToolkit().getImage(
			ResourceUtils.getUrl("resources/hourglass_working.gif"));
	
	public JHourGlass() {
		setMenus();
		setSystemTray();
	}

	private void setSystemTray() {
		tray = SystemTray.getSystemTray();

		ActionListener listener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println(new Date());
			}
		};

		trayIcon = new TrayIcon(basicImage, "Hour-glass", popup);
		trayIcon.setImageAutoSize(true);
		trayIcon.addActionListener(listener);

		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			System.err.println(e);
		}

	}

	private void setMenus() {
		popup = new PopupMenu();

		startMenuItem = new MenuItem("Start");
		startMenuItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String result = JOptionPane.showInputDialog("Setting minutes");
				if (result == null)
					return;
				timeInMinute = Integer.parseInt(result);
				startTimer();
			}
		});

		popup.add(startMenuItem);

		popup.addSeparator();

		// create menu item for the default action
		quitMenuItem = new MenuItem("Quit");
		quitMenuItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(1);

			}
		});

		popup.add(quitMenuItem);
	}

	public void startTimer() {
		startMenuItem.setEnabled(false);
		trayIcon.setImage(workingImage);
		
		timer.schedule(new JHourTimerTask(this), timeInMillis());
	}

	public void endTimer() {
		timeInMinute = 0;
		
		startMenuItem.setEnabled(true);
		trayIcon.setImage(basicImage);
	}

	public int getTimeInMinute() {
		return timeInMinute;
	}

	private int timeInMillis() {
		return timeInMinute * 60 * 1000;
	}

	public static void main(String args[]) {

		if (!SystemTray.isSupported()) {
			throw new RuntimeException("System Tray is not supported!");
		}

		new JHourGlass();
	}

}
